from django.shortcuts import render,HttpResponse,redirect
from django.contrib.auth import authenticate,login
from .forms import LoginForm,RegisterForm
from django.contrib.auth.backends import ModelBackend #身份验证后端
from django.db.models import Q #Q类构建复杂的查询
from .forms import LoginForm,RegisterForm
from django.contrib.auth.models import User
from .models import UserProfile
from django.contrib.auth.decorators import login_required

class   MyBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(Q(username=username)|Q(email=username))
            if user.check_password(password): #加密明文密码
                return user
        except Exception as e:
            return None
#使用表单提交登录数据
def login_view(request):

    if request.method != 'POST':
        form = LoginForm()
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(request, username=username, password=password)
            if user is not None:
                login(request, user)
                return redirect('/admin')
            else:
                return HttpResponse('登录失败')
    context = {'form':form}
    return render(request, 'users/login.html',context)

def register(request):
    if request.method !='POST':
        form = RegisterForm()
    else:
        form = RegisterForm(request.POST)
        if form.is_valid(): #这一行代码检查表单是否通过了数据验证。如果表单中的所有字段都符合要求，is_valid()方法将返回True，否则返回False
            new_user = form.save(commit=False) #将commit参数设置为False。不会立即将数据写入数据库。这通常用于在保存数据之前进行一些额外的操作或修改。
            new_user.set_password(form.cleaned_data.get('password'))#为新用户设置密码并进行加密处理
            new_user.username = form.cleaned_data.get('email')
            new_user.save() #此时保存到数据库
            return HttpResponse('注册成功')


    context = {'form':form} #render将数据渲染到html中，创建一个form变量值为form
    return render(request,'users/register.html',context)

@login_required(login_url='users:login')
def user_profile(request):
    user = User.objects.get(username=request.user)
    return render(request,'users/user_profile.html',{'user':user})

# Create your views here.
